package com.yanqu.road.server.gameplayer.module.activity.common;

import com.yanqu.road.dao.impl.player.CommonActivityAutoBuyDataDaoImpl;
import com.yanqu.road.entity.activity.*;
import com.yanqu.road.entity.config.goods.BuyGoodsResult;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eShopType;
import com.yanqu.road.logic.bussiness.player.UserCommonActivityBussiness;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.entity.activity.commonactivity.data.CommonActivityAutoBuyData;
import com.yanqu.road.server.gameplayer.module.activity.ActivityMallModule;
import com.yanqu.road.server.manger.activity.MallActivityMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.commonactivity.CommonActivityProto;
import com.yanqu.road.pb.cross.activity.CrossActivityProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.logic.activity.common.CommonActivityData;
import com.yanqu.road.server.logic.activity.common.condition.BaseCommonActivityCondition;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.CommonActivityMgr;
import com.yanqu.road.server.manger.activity.CommonActivityRankMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.union.UnionActivityMgr;
import com.yanqu.road.server.pb.CommonActivityPb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CommonActivityModule extends GeneralModule {

    private Map<Integer, Map<Integer, CommonActivityData>> activityDataMap;

    private Map<Integer, CommonActivityAutoBuyData> autoBuyDataMap;

    public CommonActivityModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean afterLoadData() {
        return false;
    }

    @Override
    public boolean saveData() {
        for(Map<Integer, CommonActivityData> dataMap : activityDataMap.values()) {
            for (CommonActivityData activityData : dataMap.values()) {
                for (UserActivityConditionData conditionData : activityData.getUserActivityConditionDataList()) {
                    if (conditionData.isInsertOption()) {
                        UserCommonActivityBussiness.addUserCommonActivityConditionData(conditionData);
                    } else if (conditionData.isUpdateOption()) {
                        UserCommonActivityBussiness.updateUserCommonActivityConditionData(conditionData);
                    }
                }
            }
        }
        for (CommonActivityAutoBuyData autoBuyData : autoBuyDataMap.values()) {
            if (autoBuyData.isInsertOption()) {
                new CommonActivityAutoBuyDataDaoImpl().add(autoBuyData);
            }else if (autoBuyData.isUpdateOption()) {
                new CommonActivityAutoBuyDataDaoImpl().update(autoBuyData);
            }
        }

        return true;
    }

    @Override
    public boolean loadData() {
        activityDataMap = new ConcurrentHashMap<>();
        List<ActivityInfo> activityInfoList = CommonActivityMgr.getAllOpenCommonActivityInfoList();
        List<Integer> activityIdList = new ArrayList<>();
        for(ActivityInfo activityInfo : activityInfoList){
            activityIdList.add(activityInfo.getActivityId());
        }
        Map<Integer, Map<Integer, List<UserActivityConditionData>>> userActivityConditionDataMap = UserCommonActivityBussiness.getUserActivityConditionDataMap(player.getUserId(),
                activityIdList);
        for(ActivityInfo activityInfo : activityInfoList){
            Map<Integer, List<UserActivityConditionData>> dataMap = userActivityConditionDataMap.get(activityInfo.getActivityId());
            if(null != dataMap) {
                for (Map.Entry<Integer, List<UserActivityConditionData>> dataEntry : dataMap.entrySet()) {
                    addActivity(activityInfo, dataEntry.getValue(), dataEntry.getKey(), false);
                }
            }
        }
        autoBuyDataMap = new CommonActivityAutoBuyDataDaoImpl().getCommonActivityAutoBuyData(player.getUserId());
        addNewActivity();
        return true;
    }

    @Override
    public void loginSendMsg() {
        addNewActivity();
    }

    @Override
    public void afterLogin() {
        syncActivity();
        syncAutoBuyData();
    }

    public void syncActivity(){
        Map<Integer, Map<Integer, CommonActivityData>> dataMap = new ConcurrentHashMap<>();
        List<ActivityInfo> activityInfoList = CommonActivityMgr.getAllOpenCommonActivityInfoList();
        if(activityInfoList.size() > 0) {
            for (ActivityInfo activityInfo : activityInfoList) {
                Map<Integer, CommonActivityData> tempMap = activityDataMap.get(activityInfo.getActivityId());
                if (null != tempMap) {
                    dataMap.put(activityInfo.getActivityId(), tempMap);
                }
            }
            CommonActivityProto.CommonActivityDetailMsg.Builder detailMsg = CommonActivityMgr.getCommonActivityDetailMsg(dataMap, player.getLanguage());
            player.sendPacket(Protocol.U_COMMON_ACTIVITY_DETAIL, detailMsg);
         //   autoUseActivityGoods(activityInfoList);
        }
    }

    /**
     * 同步自动购买参数
     */
    public void syncAutoBuyData(){
        CommonActivityProto.CommonActivityAutoBuySync.Builder builder = CommonActivityProto.CommonActivityAutoBuySync.newBuilder();
        for (CommonActivityAutoBuyData autoBuyData : autoBuyDataMap.values()) {
            CommonActivityProto.TypeCommonActivityAutoBuyData.Builder typeData = CommonActivityPb.parseCommonActivityAutoBuyTypeData(autoBuyData);
            builder.addData(typeData.build());
        }
        player.sendPacket(ClientProtocol.U_COMMON_ACTIVITY_SYNC_AUTO_BUY_PARAM, builder);
    }

    /**
     * 设置自动购买参数
     */
    public int setCommonActivityAutoBuyData(int activityId,int childType,Map<String,Integer> map){
        ActivityInfo openCommonActivityInfo = CommonActivityMgr.getOpenCommonActivityInfo(activityId);
        if (openCommonActivityInfo == null) {
            return GameErrorCode.E_COMMON_ACTIVITY_NO_IN_TIME;
        }
        if (openCommonActivityInfo.getChildType() != childType) {
            return GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
        }

        Map<String,Integer> childTypeMap = new ConcurrentHashMap<>();
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            String item = entry.getKey();
            int num = entry.getValue();
            if (num <= 0){
                continue;
            }
            MallInfo info = CommonActivityMgr.getMallInfoByItem(activityId, item);
            //没找到就下一个吧
            if (info == null) {
                continue;
            }

            //不是兑换商店的不给设置 下一个
            if (info.getShopType() != eShopType.CommonActivityExchangeMall.getValue()) {
                continue;
            }

            //看看奖励是不是一样
            if (info.getReward().equals(item)) {
                //系统解锁限制 不给设置
                if (!info.getSystemLimit().isEmpty()) {
                    for (Integer systemId : info.getSystemLimit()) {
                        if (!SystemOpenMgr.systemOpen(player, systemId)) {
                            continue;
                        }
                    }
                }

                //如果设置的值比限购大 拉回来
                if (num > info.getLimitBuyCount()) {
                    childTypeMap.put(item, info.getLimitBuyCount());
                } else {
                    childTypeMap.put(item, num);
                }
                continue;
            }
        }

        CommonActivityAutoBuyData data = setCommonActivityAutoBuyData(childType, childTypeMap);
        //回包
        CommonActivityProto.SetCommonActivityAutoBuyDataResp.Builder builder = CommonActivityProto.SetCommonActivityAutoBuyDataResp.newBuilder();
        builder.setRet(0);
        builder.setData(CommonActivityPb.parseCommonActivityAutoBuyTypeData(data));
        player.sendPacket(ClientProtocol.U_COMMON_ACTIVITY_SET_AUTO_BUY_PARAM, builder);
        return 0;
    }

    public synchronized CommonActivityAutoBuyData setCommonActivityAutoBuyData(int type, Map<String, Integer> map) {
        CommonActivityAutoBuyData data;
        if (!autoBuyDataMap.containsKey(type)) {
            data = new CommonActivityAutoBuyData();
            data.setUserId(player.getUserId());
            data.setChildType(type);
            data.setChooseMap(map);
            data.setInsertOption();
            autoBuyDataMap.put(type, data);
        } else {
            data = autoBuyDataMap.get(type);
            data.setChooseMap(map);
            data.setUpdateOption();
        }
        return data;
    }

    /**
     * 一键购买通用活动商品
     */
    public int autoBuyCommonActivityItem(int activityId){
        ActivityInfo openCommonActivityInfo = CommonActivityMgr.getOpenCommonActivityInfo(activityId);
        if (openCommonActivityInfo == null) {
            return GameErrorCode.E_COMMON_ACTIVITY_NO_IN_TIME;
        }
        int childType = openCommonActivityInfo.getChildType();
        CommonActivityAutoBuyData commonActivityAutoBuyData = getCommonActivityAutoBuyData(childType);
        if (commonActivityAutoBuyData == null) {
            return GameErrorCode.E_COMMON_ACTIVITY_AUTO_BUY_NO_SET;
        }
        List<String> buyResult = new ArrayList<>();
        Map<String, Integer> chooseMap = commonActivityAutoBuyData.getChooseMap();
        for (Map.Entry<String, Integer> entry : chooseMap.entrySet()) {
            MallInfo mallInfoByItem = CommonActivityMgr.getMallInfoByItem(activityId, entry.getKey());
            if (mallInfoByItem == null) {
                continue;
            }
            if (mallInfoByItem.getShopType() != eShopType.CommonActivityExchangeMall.getValue()) {
                continue;
            }
            if (entry.getValue() <= 0) {
                continue;
            }

            //系统解锁限制
            if (mallInfoByItem.getSystemLimit().size() > 0) {
                for (Integer systemId : mallInfoByItem.getSystemLimit()) {
                    if (!SystemOpenMgr.systemOpen(player, systemId)) {
                        continue;
                    }
                }
            }

            int buyNum = 0;
            int limitCount = player.getModule(ActivityMallModule.class).getLimitCount(mallInfoByItem);
            if (entry.getValue() > limitCount) {
                buyNum = limitCount;
            }else {
                buyNum = entry.getValue();
            }
            if (buyNum <= 0){
                continue;
            }

            BuyGoodsResult buyGoodsResult = player.getModule(ActivityMallModule.class).buyGoods(mallInfoByItem, buyNum);
            if (buyGoodsResult != null) {
                if (buyGoodsResult.getRet()==0){
                    buyResult.add(buyGoodsResult.getReward());
                }
            }
        }
        if (buyResult.isEmpty()) {
            return GameErrorCode.E_COMMON_ACTIVITY_AUTO_BUY_NOTHING;
        }

        CommonActivityProto.CommonActivityAutoBuyResp.Builder builder = CommonActivityProto.CommonActivityAutoBuyResp.newBuilder();
        builder.setRet(0);
        builder.addAllReward(buyResult);

        player.sendPacket(ClientProtocol.U_COMMON_ACTIVITY_AUTO_BUY, builder);
        return 0;
    }



    /**
     * 自动将活动道具转为活动积分
     * @param activityInfoList
     */
    public void autoUseActivityGoods(List<ActivityInfo> activityInfoList){
        if(null != activityInfoList){
            for(ActivityInfo activityInfo : activityInfoList){
           //     autoUseActivityGoods(activityInfo);
            }
        }
    }

    private void autoUseActivityGoods(ActivityInfo activityInfo){
        /*if(ActivityMgr.activityInShowPeriod(activityInfo) || ActivityMgr.activityInRewardPeriod(activityInfo)){//在展示期或者领奖期
            for(int goodsId : activityInfo.getCommonActivityItemList()){
                player.getModule(BagModule.class).removeCommonActivityBagItem(activityInfo, goodsId);
            }
        }*/
    }

    public void addNewActivity() {
        synchronized (this) {
            List<ActivityInfo> activityInfoList = CommonActivityMgr.getAllOpenCommonActivityInfoList();
            for (ActivityInfo activityInfo : activityInfoList) {
                Map<Integer, List<ActivityConditionInfo>> dataMap = CommonActivityMgr.getCommonActivityConditionInfoMap(activityInfo.getActivityId());
                if (null != dataMap) {
                    for (int type : dataMap.keySet()) {
                        addActivity(activityInfo, new ArrayList<>(), type, true);
                    }
                }
                Map<Integer, CommonActivityData> tempActivityDataMap = getCommonActivityDataMap(activityInfo.getActivityId());
                if (null != tempActivityDataMap) {
                    for (CommonActivityData activityData : tempActivityDataMap.values()) {
                        for (BaseCommonActivityCondition baseCommonActivityCondition : activityData.getBaseCommonActivityConditionList()) {
                            if (null != baseCommonActivityCondition) {
                                baseCommonActivityCondition.initValue();
                            }
                        }
                    }
                }
            }
        }
    }

    private Map<Integer, CommonActivityData> getCommonActivityDataMap(int activityId){
        return activityDataMap.get(activityId);
    }

    private void addActivity(ActivityInfo activityInfo, List<UserActivityConditionData> conditionDataList, int type, boolean isNew) {
        synchronized (this) {
            if (null != activityInfo) {
                if (!activityDataMap.containsKey(activityInfo.getActivityId())) {
                    activityDataMap.put(activityInfo.getActivityId(), new ConcurrentHashMap<>());
                }

                Map<Integer, CommonActivityData> dataMap = activityDataMap.get(activityInfo.getActivityId());
                if (dataMap.containsKey(type)) {
                    return;
                }
                List<ActivityConditionInfo> conditionInfoList = CommonActivityMgr.getCommonActivityConditionInfoList(activityInfo.getActivityId(), type);
                if (null == conditionInfoList) {
                    return;
                }
                for (UserActivityConditionData data : conditionDataList) {
                    UnionActivityConditionData unionActivityConditionData = CommonActivityRankMgr.getUnionActivityConditionData(data.getActivityId(), player.getUserId());
                    if (null != unionActivityConditionData) {
                        data.setUnionUid(unionActivityConditionData.getUnionUid());
                    }
                }
                CommonActivityData activityData = new CommonActivityData(player, activityInfo, conditionDataList);
                for (ActivityConditionInfo conditionInfo : conditionInfoList) {
                    if (activityData.continueAdd(conditionInfo.getType())) {
                        BaseCommonActivityCondition baseCommonActivityCondition = BaseCommonActivityCondition.createCommonActivityCondition(player, activityData, conditionInfo);
                        if (null != baseCommonActivityCondition) {
                            activityData.addCondition(baseCommonActivityCondition);
                            if (isNew) {
                                UserActivityConditionData userConditionData = ActivityMgr.initUserActivityConditionData(player, conditionInfo);
                                activityData.addUserCommonActivityConditionData(userConditionData);
                            }
                        }
                    }
                }
                dataMap.put(type, activityData);
                activityData.addToPlayer();
            }
        }
    }

    public ActivityRewardResult getRankReward(int activityId, int conditionId, boolean isCrossNotify, int crossRank) {
        ActivityRewardResult result = new ActivityRewardResult();
        ActivityInfo openActivityInfo = CommonActivityMgr.getOpenCommonActivityInfo(activityId);
        if(null == openActivityInfo){
            result.setRet(GameErrorCode.E_COMMON_ACTIVITY_NO_IN_TIME);
            return result;
        }
        ActivityConditionInfo conditionInfo = CommonActivityMgr.getCommonActivityConditionInfo(activityId, conditionId);
        if (ActivityHelper.COMMON_ACTIVITY_CONDITION_TYPE_USER != conditionInfo.getType() &&
                ActivityHelper.COMMON_ACTIVITY_CONDITION_TYPE_UNION != conditionInfo.getType() &&
                ActivityHelper.COMMON_ACTIVITY_CONDITION_TYPE_CROSS != conditionInfo.getType()) {
            result.setRet(GameErrorCode.E_COMMON_ACTIVITY_GET_REWARD_TYPE_ERROR);
            return result;
        }
        int type = conditionInfo.getType();
        Map<Integer, CommonActivityData> dataMap = activityDataMap.get(activityId);
        if(null == dataMap){
            result.setRet(GameErrorCode.E_COMMON_ACTIVITY_NO_IN_TIME);
            return result;
        }
        CommonActivityData activityData = dataMap.get(type);
        if (null == activityData) {
            result.setRet(GameErrorCode.E_COMMON_ACTIVITY_NO_IN_TIME);
            return result;
        }
        if(!ActivityMgr.activityInRewardPeriod(openActivityInfo)){
            result.setRet(GameErrorCode.E_COMMON_ACTIVITY_NO_IN_REWARD_TIME);
            return result;
        }
        if(!ActivityMgr.activityInCanRewardPeriod(openActivityInfo)){
            result.setRet(GameErrorCode.E_COMMON_ACTIVITY_REWARD_SETTLEMENT_TIME);
            return result;
        }
        UserActivityConditionData conditionData = activityData.getFirstConditionData();
        if(null == conditionData){
            result.setRet(GameErrorCode.E_COMMON_ACTIVITY_NO_JOIN);
            return result;
        }
        if (conditionData.isGetReward()) {
            result.setRet(GameErrorCode.E_COMMON_ACTIVITY_HAS_GET_REWARD);
            return result;
        }
        int myRank;
        boolean isMaster = false;
        UnionActivityConditionData unionActivityConditionData = null;
        if(ActivityHelper.COMMON_ACTIVITY_CONDITION_TYPE_CROSS == conditionInfo.getType()){
            if(isCrossNotify){
                myRank = crossRank;
            }else {
                //发送请求到跨服获取排名
                CrossActivityProto.CrossActivityGetRewardReqMsg.Builder reqMsg = CrossActivityProto.CrossActivityGetRewardReqMsg.newBuilder();
                reqMsg.setActivityId(activityId);
                reqMsg.setConditionId(conditionId);
                YanQuMessage pkg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_COMMON_ACTIVITY_GET_REWARD, reqMsg);
                GamePlayerMgr.sendPacket(player.getUserId(), pkg);
                return result;
            }
        }else {
            if (ActivityHelper.COMMON_ACTIVITY_CONDITION_TYPE_USER == type) {
                myRank = CommonActivityRankMgr.getCommonActivityRank(activityId, player.getUserId());
            } else {
                unionActivityConditionData = CommonActivityRankMgr.getUnionActivityConditionData(activityId, player.getUserId());
                if (null == unionActivityConditionData) {
                    result.setRet(GameErrorCode.E_COMMON_ACTIVITY_NO_JOIN);
                    return result;
                }
                myRank = CommonActivityRankMgr.getCommonActivityUnionRank(activityId, unionActivityConditionData.getUnionUid());
                isMaster = (unionActivityConditionData.getUnionBaseInfo().getMasterUserId() == player.getUserId());
            }
        }
        conditionInfo = CommonActivityMgr.getCommonActivityConditionInfoByRank(activityId, type, myRank);
        if (conditionInfo != null) {// 添加奖励
            if(isMaster && ActivityHelper.COMMON_ACTIVITY_CONDITION_TYPE_UNION == type){
                player.getModule(CurrencyModule.class).addCurrency(conditionInfo.getMasterReward(), eLogMoneyType.Activity, eLogMoneyType.CommonActivityUnionRankReward);
                result.setReward(conditionInfo.getMasterRewardStr());
            }else {
                if(ActivityHelper.COMMON_ACTIVITY_CONDITION_TYPE_UNION == type) {
                    result.setReward(UnionActivityMgr.getUnionMemberPositionDataReward(unionActivityConditionData,conditionInfo,player.getUserId()));
                    player.getModule(CurrencyModule.class).addCurrency(result.getReward(), eLogMoneyType.Activity, eLogMoneyType.CommonActivityUnionRankReward);
                }else {
                    player.getModule(CurrencyModule.class).addCurrency(conditionInfo.getReward(), eLogMoneyType.Activity, eLogMoneyType.CommonActivityRankReward);
                    result.setReward(conditionInfo.getRewardStr());
                }
            }
        }
        conditionData.setGetReward(true);
        onActivityDataChange(activityData);
        activityData.finish(conditionData.getConditionId());
        LogMgr.addLogCommonActivityRankReward(player.getUserId(), activityId, type, myRank, result.getReward());
        return result;
    }

    public void nickNameChange(){
        List<ActivityInfo> openActivityInfoList = CommonActivityMgr.getOpenCommonActivityInfoList(eActivityType.CommonActivity.getValue());
        for(ActivityInfo activityInfo : openActivityInfoList) {
            Map<Integer, CommonActivityData> dataMap = activityDataMap.get(activityInfo.getActivityId());
            if(null != dataMap) {
                CommonActivityData activityData = dataMap.get(ActivityHelper.COMMON_ACTIVITY_CONDITION_TYPE_UNION);
                if(null != activityData){
                    List<UserActivityConditionData> dataList = activityData.getUserActivityConditionDataList();
                }
            }
        }
    }

    public void onActivityDataChange(CommonActivityData commonActivityData){
        CommonActivityProto.CommonActivityDataMsg.Builder dataMsg = CommonActivityPb.parseCommonActivityDataMsg(commonActivityData);
        if(null != dataMsg) {
            player.sendPacket(Protocol.U_COMMON_ACTIVITY_DATA_SYNC, dataMsg);
        }
    }

    public UserActivityConditionData getUserActivityConditionData(int activityId){
        Map<Integer, CommonActivityData> dataMap = activityDataMap.get(activityId);
        if(null != dataMap){
            CommonActivityData activityData = dataMap.get(ActivityHelper.COMMON_ACTIVITY_CONDITION_TYPE_UNION);
            if(null != activityData){
                return activityData.getFirstConditionData();
            }
        }
        return null;
    }

    /**
     * 根据子类型获取自动购买
     * @param childType
     * @return
     */
    public CommonActivityAutoBuyData getCommonActivityAutoBuyData(int childType){
        return autoBuyDataMap.get(childType);
    }
}
